<template>
  <el-button
    class="button button--primary"
    :class="user.followed ? 'button--grey' : 'button--blue'"
    @click="follow"
    :loading="loading"
    style="width: 98px;"
  >
    <template v-if="user.followed">已关注</template>
    <template v-else>
      <i v-if="!loading" class="el-icon-plus"></i>
      关注
    </template>
  </el-button>
</template>

<script>
import { mapState } from 'vuex';
import { formatUser } from '@/views/users/format';

export default {
  name: 'follow-button',
  props: {
    user: Object,
  },
  data() {
    return {
      loading: false,
    };
  },
  computed: {
    ...mapState({ curUser: 'currentUser' }),
  },
  methods: {
    follow() {
      if (this.curUser.id === this.user.id) {
        this.$message.error('您不能关注您自己');
        return;
      }
      this.loading = true;
      this.$api.other.vote({
        votePosition: 'User',
        votePositionId: this.user.id,
        voteAction: 'attention',
        voteState: !this.user.followed,
      })
        .then((res) => {
          if (!this.user.followed) this.$message.success('关注成功');
          this.$emit('attention', formatUser(res.data));
        }).catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
};
</script>

<style></style>
